package servlet;

import javax.imageio.ImageIO;
import javax.servlet.annotation.WebServlet;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/checkcode")
public class CheckcodeServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request, response);

    }
    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        //1.鍦ㄥ唴瀛樼敓鎴愪竴涓浘鐗�
        int width = 120;
        int height = 30;
        BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g =(Graphics2D) img.getGraphics();//鑾峰彇鐢荤瑪锛�
        g.setColor(Color.white);//璁剧疆棰滆壊
        g.fillRect(0,0,width,height);//濉厖鐭╁舰锛�
        g.setColor(Color.BLUE);
        g.drawRect(0,0,width-1,height-1);//鐢昏竟妗�
        String words = "ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz123456789";//缁欏畾鏁版嵁锛�
        g.setFont(new Font("闅朵功",Font.BOLD,20));//璁剧疆瀛椾綋
        Random random = new Random();//缁欏畾鍥涗釜闅忔満鏁帮紱
        char []Chars = new char[4];
        //request.getSession().setAttribute("identifyingCode", random);
        int x = 20,y = 20;
        for(int i = 0;i<4;i++){
            int jiaodu = random.nextInt(60)-30;
            double hudu = jiaodu*Math.PI/180;
            g.rotate(hudu,x,y);
            //鍦╳ords鐨勯暱搴﹁寖鍥村唴鑾峰彇涓�涓殢鏈虹殑绱㈠紩鍊�
            int index = random.nextInt(words.length());
            //閫氳繃閭ｄ釜绱㈠紩鍊兼壘鍒扮浉搴旂殑瀛楁瘝
            //char ch = words.charAt(index);
            Chars[i]=words.charAt(index);
            g.rotate(-hudu,x,y);
            //g.drawString(""+ch,x,y);
            g.drawString(""+Chars[i],x,y);
            x+=20;
        }
        String identifyingCode = new String(Chars);
        request.getSession().setAttribute("identifyingCode", identifyingCode);
        //鐢诲洓鏉＄嚎
        g.setColor(Color.red);
        int x1,x2,y1,y2;
        for(int i = 0;i<4;i++){
            x1 = random.nextInt(width);
            y1 = random.nextInt(height);
            x2 = random.nextInt(width);
            y2 = random.nextInt(height);
            g.drawLine(x1,y1,x2,y2);
        }

//鏄剧ず鍒扮敾甯冮〉闈紱
        ImageIO.write(img,"jpg",response.getOutputStream());
    }
}

